package com.nix.web.controller.until.verification;

import org.springframework.stereotype.Service;

import java.util.Random;

/**
 * 根据ASCII码获取随机验证码，获取就加密
 * 需要的字符的ASCII码对应的范围
 * 0-9 48-57
 * A-Z 65-90
 * a-z 97-122
 *
 * @ 64
 * Create by zhangpe0312@qq.com on 2017/12/31.
 */
@Service
public class VerificationCode {


    public String getCode(int[] codes) {
        StringBuilder buff = new StringBuilder();
        for (int code :
                codes) {
            buff.append((char) code);
        }
        return buff.toString();
    }

    /**
     * 生成六位证码的ASCII
     * 生成的验证码为 大写，小写，数字组成
     *
     * @return
     */
    private int[] getRandom() {
        int[] bytes = new int[6];
        for (int i = 0; i < 6; i++) {
            int temp = getByte(0, 3);
            switch (temp) {
                case 0:
                    bytes[i] = getByte(48, 10);
                    break;
                case 1:
                    bytes[i] = getByte(65, 26);
                    break;
                case 2:
                    bytes[i] = getByte(97, 26);
                    break;
//                case 3:bytes[i] = 64;
//                break;
                default:
                    i--;
            }
            System.out.print(bytes[i] + " value = " + (char) bytes[i] + " ");
        }
        return bytes;
    }

    /**
     * 指定范围的随机数
     *
     * @return
     */
    private int getByte(int start, int end) {
        Random random = new Random();
        return random.nextInt(end) + start;
    }

    public String getCode() {
        return getCode(getRandom());
    }

}
